package com.corpgovernment.organization.service.impl;

import com.corpgovernment.api.basic.vo.MbUserDeviceVo;
import com.corpgovernment.organization.entity.db.MbUserDevice;
import com.corpgovernment.organization.mapper.MbUserDeviceMapper;
import com.corpgovernment.organization.service.IMbUserDeviceService;
import com.ctrip.corp.obt.generic.utils.CollectionUtils;
import com.ctrip.corp.obt.generic.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class UserDeviceServiceImpl implements IMbUserDeviceService {

    @Autowired
    private MbUserDeviceMapper userDeviceMapper;

    @Override
    public void deleteBy(String uid, String uuid, String deviceId) {
        if (StringUtils.isEmpty(uid)) {
            return;
        }
        log.info("删除绑定设备2:uid:{},uuid:{},deviceId:{}",uid,uuid,deviceId);
        userDeviceMapper.delete(new MbUserDevice(uid, uuid, deviceId));
    }

    @Override
    public void saveOrUpdate(MbUserDeviceVo model) {
        if (model == null || StringUtils.isEmpty(model.getUid())) {
            return;
        }
        try {
            List<MbUserDevice> list = userDeviceMapper.select(new MbUserDevice(model.getUid(), model.getUuid(), model.getDeviceId(), model.getAppId(), model.getOsVersion()));
            MbUserDevice param = this.convert(model);
            if (CollectionUtils.isEmpty(list)) {
                userDeviceMapper.insertSelective(param);
            } else {
                userDeviceMapper.update(param);
            }
        } catch (Exception e) {
            log.error("保存登录设备号异常" + e.toString());
        }

    }

    private MbUserDevice convert(MbUserDeviceVo source) {
        if (source == null) {
            return null;
        }
        MbUserDevice target = new MbUserDevice();
        BeanUtils.copyProperties(source, target);
        return target;
    }
}
